import { type FormEvent, useContext, useState } from 'react';
import useToast from '@/hooks/useToast';
import { useMutation } from '@tanstack/react-query';
import { queryQqAuthUrl } from '@/services/api';
import { LoginPageContext } from '@/contexts/login';

export default function QqLogin() {
  const {
    source: { path: data },
    translatedFields,
  } = useContext(LoginPageContext)!;
  const [disableLogin, setDisableLogin] = useState(false);
  const { show } = useToast();

  const queryQqAuthUrlMutation = useMutation(queryQqAuthUrl);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const qqConfig = data.qqConfig;
      if (!qqConfig || !qqConfig.enable) {
        show({
          type: 'DANGER',
          message: translatedFields.qqLoginDisabled,
        });
        return;
      }

      const url = (await queryQqAuthUrlMutation.mutateAsync({
        data: { alias: '' },
      })) as string;
      setDisableLogin(true);

      show({
        message: translatedFields.qqAuthorizationPrompt,
        type: 'PRIMARY',
      });

      setTimeout(() => {
        show({
          message: translatedFields.redirecting,
          type: 'PRIMARY',
        });
      }, 1000);

      setTimeout(() => {
        location.href = url;
      }, 1500);
    } catch (e) {
      queryQqAuthUrlMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  return (
    <form onSubmit={onSubmit}>
      {data.qqConfig && data.qqConfig.enable ? (
        <div className="my-3">
          <button
            disabled={queryQqAuthUrlMutation.isLoading || disableLogin}
            type="submit"
            className="btn btn-outline-primary mt-4 mb-3 w-100"
          >
            {queryQqAuthUrlMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            {disableLogin ? (
              <span>{translatedFields.redirecting}</span>
            ) : (
              <span>{translatedFields.loginPrompt}</span>
            )}
          </button>
        </div>
      ) : (
        <div className="my-3">
          <button
            disabled
            type="submit"
            className="btn btn-outline-primary mt-4 mb-3 w-100"
          >
            {translatedFields.qqLoginDisabled}
          </button>
        </div>
      )}
    </form>
  );
}
